package de.koller.reason.gui.component.button;

import de.koller.reason.gui.GUIInput;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class ButtonHandler {
	
	public static final int REGOGNIZED_BUTTON = 0;
	private IButton previousOver = null;
	
	public void update( Set<IButton> buttons, GUIInput input ) {
		//@todo: check if panel or something overlap buttons
		
		float mx = input.getMouseX();
		float my = input.getMouseY();

		IButton e = eligbleButton( buttons, mx, my );
		
		if( e != previousOver && previousOver != null )
			previousOver.buttonEvent( new ButtonEvent( ButtonStatus.MouseLess, mx, my, -1 ) );
		
		previousOver = e;
		
		if( previousOver == null )
			return;
		
		if( input.isMouseReleased( REGOGNIZED_BUTTON ) )
			previousOver.buttonEvent( new ButtonEvent( ButtonStatus.MouseReleased, mx, my, REGOGNIZED_BUTTON ) );
		else if( input.isMouseDown( REGOGNIZED_BUTTON ) )
			previousOver.buttonEvent( new ButtonEvent( ButtonStatus.MouseDown, mx, my, REGOGNIZED_BUTTON ) );
		else
			previousOver.buttonEvent( new ButtonEvent( ButtonStatus.MouseOver, mx, my, REGOGNIZED_BUTTON ) );
	}
	
	private IButton eligbleButton( Set<IButton> buttons, float mx, float my ) {
		List<IButton> elg = new ArrayList<>();
		
		for( IButton b : buttons )
			if( isInBound( mx, my, b ) )
				elg.add( b );
		
		if( elg.isEmpty() )
			return null;
		
		IButton e = elg.get( 0 );
		for( int i = 1; i < elg.size(); i++ ) {
			IButton b = elg.get( i );
			if( b.getDimension().getZ() > e.getDimension().getZ() )
				e = b;
		}
			
		return e;
	}
	
	private boolean isInBound( float mx, float my, IButton b ) {
		if( mx < b.getDimension().getX() )
			return false;
		if( mx > b.getDimension().getX() + b.getDimension().getWidth() )
			return false;
		if( my < b.getDimension().getY() )
			return false;
		if( my > b.getDimension().getY() + b.getDimension().getHeight() )
			return false;
		return true;
	}
	
}
